<style lang=less scoped>
	@import "../../variables.less";
	@import "../../resource/common.less";

	@currentWidth: 965px;
	@attachWidth: 100px;
</style>
<template>
	<div>
		<div class="mainContent">
			<div class="head">
				维保计划
				<div class="attach">
					<Button @click="add" ghost icon="ios-plus" size=small>添加计划</Button>
				</div>
			</div>
			<Table :columns="columns" :data="dataSource" :height="height" :loading="tableLoading" size="small">
				<Loading slot="loading" />
			</Table>
			<Page :current.sync="page" :pageSize="pageSize" :total="total" @on-change="pageChange"
				show-total
				simple
				size="small" style="text-align: right;margin-top: 6px" />
		</div>
		<Modal :loading=true :title="title" @on-ok="submit" v-model="showModal">
			<Form :label-width=120 :model="form" ref="form">
				<FormItem label="名称">
					<Input :readonly=disable v-model="form.name" />
				</FormItem>
				<FormItem label="班组">
					<Select :disabled=disable v-model="form.template">
						<Option :key="i.id" :value="i.id" v-for="i in template">{{i.name}}</Option>
					</Select>
				</FormItem>
				<FormItem label="维保类型">
					<CheckboxGroup v-model="form.type">
						<Checkbox :disabled=disable :key="i" :label="i" v-for="i in type"> {{i}}</Checkbox>
					</CheckboxGroup>
				</FormItem>
				<FormItem label="楼宇">
					<CheckboxGroup v-model="form.facility">
						<Checkbox :disabled=disable :key="i.id" :label="i.id" v-for="i in facility">{{i.name}}
						</Checkbox>
					</CheckboxGroup>
				</FormItem>
				<FormItem label="起止时间">
					<DatePicker :options="options" :readonly="disable" type="daterange" v-model="form.duration" />
				</FormItem>
				<FormItem label="是否循环">
					<RadioGroup v-model="form.loop">
						<Radio :disabled=disable :label="0">否</Radio>
						<Radio :disabled=disable :label="1">是</Radio>
					</RadioGroup>
				</FormItem>
				<template v-if="form.loop===1">
					<FormItem label="循环周期">
						<InputNumber :min=1 :readonly="disable" v-model="form.frequency" />
						<Select :disabled=disable style="width: 80px" v-model="form.frequencyUnit">
							<Option value="年">年</Option>
							<Option value="月">月</Option>
							<Option value="周">周</Option>
							<Option value="日">日</Option>
						</Select>
					</FormItem>
					<FormItem label="循环时间">
						<DatePicker :disabled=disable :options="options" type="daterange" v-model="form.loopTime" />
					</FormItem>
				</template>
			</Form>
		</Modal>
	</div>
</template>

<script lang=ts>
	import { Component, Vue } from "vue-property-decorator";
	import {
		Button,
		ButtonGroup,
		Checkbox,
		CheckboxGroup,
		DatePicker,
		Form,
		FormItem,
		Input,
		InputNumber, Message,
		Modal,
		Option,
		Page,
		Radio,
		RadioGroup,
		Select,
		Table
	} from "view-design";
	import request from "@/request";
	import moment from "moment";
	import qs from "qs";
	import Loading from "@/components/loading/Loading.vue";
	import { CreateElement, VNode } from "vue";

	@Component({
		components: {
			Modal,
			Form,
			FormItem,
			Input,
			Radio,
			RadioGroup,
			Checkbox,
			CheckboxGroup,
			DatePicker,
			Select,
			InputNumber,
			Option,
			Table,
			Page,
			Loading,
			ButtonGroup,
			Button,
			Message
		}
	})
	export default class MaintenancePlan extends Vue {
		showModal:boolean = false;
		title:string = "添加计划";
		template:{ name:string, id:number }[] = [];
		type:string[] = [ "物业", "电梯", "清洁", "紧固", "润滑", "检测", "更换", "其它" ];
		facility:{ name:string, id:number }[] = [];
		form = {
			name: "",
			template: 0,
			type: [],
			facility: [],
			loopTime: [ new Date(), new Date(Date.now() + 3600 * 1000 * 24 * 365) ],
			duration: [ new Date(), new Date(Date.now() + 3600 * 1000 * 24 * 365) ],
			loop: 0,
			frequency: 1,
			frequencyUnit: "月"
		};
		readonly options = {
			disabledDate (date:Date):boolean {
				return date && date.valueOf() < Date.now() - 24 * 3600 * 1000;
			}
		};
		page:number = 1;
		columns = [
			{
				title: "楼宇",
				key: "facilityName",
				align: "center",
				width: 80
			},
			{
				title: "名称",
				key: "name",
				align: "center",
				ellipsis: true,
				width: 120
			},
			{
				title: "起止时间",
				key: "duration",
				align: "center",
				width: 148
			},
			{
				title: "循环时间",
				key: "loop",
				align: "center",
				width: 148
			},
			{
				title: "类型",
				width: 80,
				align: "center",
				key: "tp"
			},
			{
				title: "负责班组",
				key: "template_name",
				width: 160,
				align: "center",
				ellipsis: true,
				tooltip: true
			},
			{
				title: "操作",
				width: 220,
				align: "center",
				render: (h:CreateElement, params:any):VNode => {
					if (params.row.button) {
						return h(ButtonGroup,
							{},
							[
								h(Button, {
									props: {
										size: "small",
										ghost: true
									},
									on: {
										click: () => {
											this.edit(params.row);
										}
									}
								}, "编辑"),
								h(Button, {
									props: {
										size: "small",
										ghost: true
									},
									on: {
										click: () => {
											this.remove(params.row);
										}
									}
								}, "删除"),
								((buttons) => {
									if (buttons) {
										return buttons.map((c:string) => {
											return h(Button, {
												props: {
													size: "small",
													ghost: true
												},
												on: {
													click: () => {
														// @ts-ignore
														Message.info("提交中，请稍候");
														request({
															url: "/device/projecttasktype/" + params.row.id + "/",
															data: {
																button: c
															},
															method: "patch"
														}).then(() => {
															this.pageChange(this.page);
														});
													}
												}
											}, c);
										});
									}
								})(params.row.button)
							]
						);
					} else {
						return h(ButtonGroup,
							[
								h(Button, {
									props: {
										size: "small",
										ghost: true
									},
									on: {
										click: () => {
											this.edit(params.row, true);
										}
									}
								}, "详情"),
								h(Button, {
									props: {
										size: "small",
										ghost: true
									},
									on: {
										click: () => {
											this.remove(params.row);
										}
									}
								}, "删除")
							]
						);
					}
				}
			}
		];
		dataSource:any[] = [];
		tableLoading:boolean = true;
		total:number = 0;
		disable:boolean = true;
		private id:number = 0;

		get height ():number {
			return document.body.clientHeight - 224;
		}

		get pageSize ():number {
			return Math.floor((this.height - 36) / 40);
		}

		add () {
			this.disable = false;
			this.id = 0;
			this.form = {
				name: "",
				template: this.template[ 0 ].id,
				type: [],
				facility: [],
				loopTime: [ new Date(), new Date(Date.now() + 3600 * 1000 * 24 * 365) ],
				duration: [ new Date(), new Date(Date.now() + 3600 * 1000 * 24 * 365) ],
				loop: 0,
				frequency: 1,
				frequencyUnit: "月"
			};
			this.showModal = true;
			this.title = "添加计划";
		}

		edit (row:any, flag:boolean = false) {
			this.showModal = true;
			this.disable = flag;
			// this.title = '修改维保策略';
			this.title = "修改维保计划";
			this.form.name = row.name;
			this.form.template = this.template.find(t => t.name === row.template_name)!.id;
			this.form.type = row.tp.length > 0 ? row.tp.split(",") : [];
			this.form.duration = [ new Date(row.firstEventstartTime), new Date(row.firstEventendTime) ];
			this.form.frequency = row.frequency;
			this.form.frequencyUnit = row.frequencyUnit;
			this.form.loopTime = [ new Date(row.startTime), new Date(row.endTime) ];
			this.form.facility = row.facilitys.map((t:string) => {
				const temp = t.match(/(?<=\/)\d+(?=\/)/);
				return temp ? parseInt(temp[ 0 ]) : "";
			});
			this.form.loop = row.iscircle ? 1 : 0;
			this.id = row.id;
		}

		remove (row:any) {
			// @ts-ignore
			Modal.confirm({
				title: "确认操作",
				content: `<p>确认删除：${ row.name }?</p>`,
				loading: true,
				onOk: () => {
					request({
						url: "/device/taskopt/",
						data: {
							tid: row.id,
							opt: "del"
						},
						method: "post",
						transformRequest: [ function (data) {
							return qs.stringify(data, { encode: false, arrayFormat: "brackets" });
						} ]
					}).then(() => {
						// @ts-ignore
						Modal.remove();
						// @ts-ignore
						Message.info("删除成功");
						this.pageChange(this.page);
					});
				}
			});
		}

		submit () {
			const info = this.form;
			let payload = {
				opt: /添加/.test(this.title) ? "create" : "change",
				name: info.name,
				template: info.template,
				frequency: info.frequency,
				frequencyUnit: info.frequencyUnit,
				facilitys: info.facility,
				firstEventstartTime: moment(info.duration[ 0 ]).format("YYYY-MM-DD"),
				firstEventendTime: moment(info.duration[ 1 ]).format("YYYY-MM-DD"),
				iscircle: info.loop === 1,
				tp: info.type.join("$"),
				daterange: [ moment(info.loopTime[ 0 ]).format("YYYY-MM-DD"), moment(info.loopTime[ 1 ]).format("YYYY-MM-DD") ]
			};
			if (this.id > 0) {
				// @ts-ignore
				payload.id = this.id;
			}
			request({
				method: "post",
				url: "/device/taskopt/",
				data: payload,
				transformRequest: [ function (data) {
					return qs.stringify(data, { encode: false, arrayFormat: "brackets" });
				} ]
			}).then(() => {
				this.showModal = false;
				this.pageChange(this.page);
			});
		}

		pageChange (page:number) {
			this.tableLoading = true;
			request({
				url: "/device/projecttasktype/",
				params: {
					pagesize: this.pageSize,
					page
				}
			}).then(({ data }) => {
				this.tableLoading = false;
				this.dataSource = data.results.map((value:any) => ({
					...value,
					duration: value.firstEventstartTime + "~" + value.firstEventendTime,
					facilityName: value.facilitys_obj.map((t:any) => t.name).join(),
					loop: value.startTime + "~" + value.endTime,
					tp: value.tp.split("$").join()
				}));
				this.total = data.count;
				this.tableLoading = false;
			}).catch(() => {
				this.page--;
				this.pageChange(page - 1);
			});
		}

		mounted ():void {
			this.pageChange(1);
			request({
				url: "/prj/facility/",
				params: {
					ordering: "sequence"
				}
			}).then(({ data }) => {
				this.facility = data.map((t:any) => ({
					id: t.id,
					name: t.name
				}));
			});
			request({
				url: "/repair/rest/flowtemplate/",
				params: {
					flowtype: 2,
					"responsible_party!": 2
				}
			}).then(({ data }) => {
				this.template = data;
			});
		}
	}
</script>
